﻿using Mozi.HttpEmbedded.Encode;
using Mozi.HttpEmbedded.Extension;
using System;
using System.Collections.Generic;

namespace Mozi.Live.RTP
{
    /// <summary>
    /// RTCP BYE报文
    /// </summary>
    public class RTCPGoodbyePackage : AbsRTCPPackage
    {
        /// <summary>
        /// 源标识符 同步源|贡献源
        /// </summary>
        public List<uint> Identifiers { get; set; }
        /// <summary>
        /// 原因说明的长度
        /// </summary>
        public byte ReasonLength { get; set; }
        /// <summary>
        /// 原因说明
        /// </summary>
        public string Reason { get; set; }
        /// <summary>
        /// 包类型
        /// </summary>
        public override RTCPPackageType PackageType
        {
            get
            {
                return RTCPPackageType.Goodbye;
            }
            set
            {
                return;
            }
        }
        /// <summary>
        /// 实例化
        /// </summary>
        public RTCPGoodbyePackage()
        {
            Identifiers = new List<uint>();
        }
        /// <summary>
        /// 打包数据流
        /// </summary>
        /// <returns></returns>
        public override byte[] Pack()
        {
            List<byte> buffer = new List<byte>();
            //TODO =1有问题;Reason长度未控制<255
            ReportCount = (byte)Identifiers.Count;
            buffer.AddRange(PackHeader());
            byte[] reason = StringEncoder.Encode(Reason);
            ReasonLength = (byte)reason.Length;
            buffer.Add(ReasonLength);
            buffer.AddRange(reason);

            //最后计算长度
            byte[] data = buffer.ToArray();
            Length = (ushort)(data.Length / 4 - 1);
            Array.Copy(Length.ToBigEndian(), 0, data, 2, 2);
            return data;
        }
        /// <summary>
        /// 解析Goodbye
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static new RTCPGoodbyePackage Parse(byte[] data)
        {
            RTCPGoodbyePackage pack = new RTCPGoodbyePackage();
            byte[] head = new byte[4];
            Array.Copy(data, 0, head, 0, 4);
            pack.ParseHeader(head);
            int offset = 4;
            pack.Identifiers = new List<uint>();
            for(int i = 0; i < pack.ReportCount; i++)
            {
                uint iSSRC = data.GetBigEndianUInt32(offset);
                pack.Identifiers.Add(iSSRC);
                offset += 4;
                
            }
            byte lenReason = data[offset];
            if (lenReason > 0&&offset<pack.Length)
            {
                byte[] arrReason = new byte[lenReason];
                Array.Copy(data, offset + 1, arrReason, 0, arrReason.Length);
                pack.Reason=StringEncoder.Decode(arrReason);
            }
            return pack;
        }
    }
}
